package com.longshihan.carservice.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.longshihan.carservice.constant.WebConst;
import com.longshihan.carservice.exception.BusinessException;
import com.longshihan.carservice.http.APIResponse;
import com.longshihan.carservice.model.UserDomain;
import com.longshihan.carservice.service.user.UserService;
import com.longshihan.carservice.utils.GsonUtils;
import com.longshihan.carservice.utils.TaleUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Api("登录相关接口")
@Controller
@RequestMapping(value = "/admin")
public class AuthController extends BaseController {


    @Autowired
    private UserService userService;

    /**
     * 微信的服务
     */
    @Autowired
    private WxMaService wxService;

    @ApiOperation("跳转登录页")
    @GetMapping(value = "/login")
    public String login() {
        return "admin/login";
    }

    @ApiOperation("登录")
    @PostMapping(value = "/login")
    @ResponseBody
    public APIResponse toLogin(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "username", value = "用户名", required = true)
            @RequestParam(name = "username", required = true)
                    String username,
            @ApiParam(name = "password", value = "密码", required = true)
            @RequestParam(name = "password", required = true)
                    String password,
            @ApiParam(name = "remeber_me", value = "记住我", required = false)
            @RequestParam(name = "remeber_me", required = false)
                    String remeber_me
    ) {
        Integer error_count = cache.get("login_error_count");
        try {
            UserDomain userInfo = userService.getUserInfoByCond(username, password);
            request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, userInfo);
            if (StringUtils.isNotBlank(remeber_me)) {
                TaleUtils.setCookie(response, userInfo.getUid());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            error_count = null == error_count ? 1 : error_count + 1;
            if (error_count > 3) {
                return APIResponse.fail("您输入密码已经错误超过3次，请10分钟后尝试");
            }
            cache.set("login_error_count", error_count, 10 * 60);
            String msg = "登录失败";
            if (e instanceof BusinessException) {
                msg = e.getMessage();
            } else {
                logger.error(msg, e);
            }
            return APIResponse.fail(msg);
        }

        return APIResponse.success();

    }


    @ApiOperation("注册")
    @PostMapping(value = "/rigister")
    @ResponseBody
    public APIResponse toRigister(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "username", value = "用户名", required = true)
            @RequestParam(name = "username", required = true)
                    String username,
            @ApiParam(name = "password", value = "密码", required = true)
            @RequestParam(name = "password", required = true)
                    String password) {
        try {
            UserDomain userDomain = new UserDomain();
            userDomain.setUsername(username);
            userDomain.setPassword(TaleUtils.MD5encode(username + password));
            userService.registerUserDomain(username, password);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return APIResponse.fail(e.getMessage());
        }
        return APIResponse.success();
    }

    /**
     * 注销
     *
     * @param session
     * @param response
     */
    @RequestMapping("/logout")
    public void logout(HttpSession session, HttpServletResponse response, org.apache.catalina.servlet4preview.http.HttpServletRequest request) {
        session.removeAttribute(WebConst.LOGIN_SESSION_KEY);
        Cookie cookie = new Cookie(WebConst.USER_IN_COOKIE, "");
        cookie.setValue(null);
        cookie.setMaxAge(0);// 立即销毁cookie
        cookie.setPath("/");
        response.addCookie(cookie);
        try {
            response.sendRedirect("/admin/login");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("注销失败", e);
        }
    }

    @ApiOperation("查询微信信息")
    @PostMapping(value = "/createWeixinUser")
    @ResponseBody
    public APIResponse getWeixinById(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "openID", value = "微信的OPENID", required = true)
            @RequestParam(name = "openID", required = true) String openID) {
        try {
            UserDomain userDomain= userService.getUserInfoByWeChatId(openID);
            return APIResponse.success(GsonUtils.toJsonString(userDomain));
        } catch (Exception e) {
            logger.error(e.getMessage());
            return APIResponse.fail(e.getMessage());
        }

    }

    @ApiOperation("获取用户信息")
    @PostMapping(value = "/getUserById")
    @ResponseBody
    public APIResponse getUserById(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "uid", value = "用户名ID", required = true)
            @RequestParam(name = "uid", required = true) Integer uid) {
        try {
            userService.getUserInfoById(uid);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return APIResponse.fail(e.getMessage());
        }
        return APIResponse.success();
    }

    /**
     * 微信登陆接口
     */
    @ApiOperation("微信获取用户信息")
    @GetMapping("/wechatlogin")
    @ResponseBody
    public APIResponse wechatlogin(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "weChatCode", value = "微信的code", required = true)
            @RequestParam(name = "weChatCode", required = true) String weChatCode
    ) {
        if (StringUtils.isBlank(weChatCode)) {
            return APIResponse.fail("empty jscode");
        } else {
            try {
                WxMaJscode2SessionResult session = this.wxService.getUserService().getSessionInfo(weChatCode);
                logger.info(session);
                UserDomain userDomain= userService.getUserInfoByWeChatId(session.getOpenid());
                if (userDomain!=null){
                    //有数据，返回UID
                    return APIResponse.success(GsonUtils.toJsonString(userDomain));
                }else {
                    //无数据，插入数据，返回UID
                    int userDomain1=  userService.registerUserDomainByWechat(session.getOpenid(),"");
                    if (userDomain1!=1){
                        return APIResponse.fail("插入失败");
                    }else {
                        UserDomain userDomain2= userService.getUserInfoByWeChatId(session.getOpenid());
                        if (userDomain2!=null) {
                            //有数据，返回UID
                            return APIResponse.success(GsonUtils.toJsonString(userDomain2));
                        }else {
                            return APIResponse.fail("更新成功但是查询失败");
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                return APIResponse.fail(e.toString());
            }
        }
    }

    @ApiOperation("微信获取用户信息详情")
    @GetMapping("/wechatloginInfo")
    @ResponseBody
    public APIResponse info(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(name = "sessionKey", value = "微信的sessionKey", required = true)
            @RequestParam(name = "sessionKey", required = true) String sessionKey,
            @ApiParam(name = "signature", value = "微信的signature", required = true)
            @RequestParam(name = "signature", required = true) String signature,
            @ApiParam(name = "rawData", value = "微信的rawData", required = true)
            @RequestParam(name = "rawData", required = true) String rawData,
            @ApiParam(name = "encryptedData", value = "微信的encryptedData", required = true)
            @RequestParam(name = "encryptedData", required = true) String encryptedData,
            @ApiParam(name = "iv", value = "微信的iv", required = true)
            @RequestParam(name = "iv", required = true) String iv

    ) {
        // 用户信息校验
        if (!this.wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return APIResponse.fail("user check failed");
        }else {
            // 解密用户信息
            WxMaUserInfo userInfo = this.wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
            logger.info(GsonUtils.toJsonString(userInfo));
            return APIResponse.success();
        }
    }
}
